﻿using Core.Models;
using Core.Tenant.Dtos;
using Core.Tenant.Features.ActivateTenant;
using Core.Tenant.Features.AssignPermission;
using Core.Tenant.Features.CreateTenant;
using Core.Tenant.Features.DisableTenant;
using Core.Tenant.Features.GetById;
using Core.Tenant.Features.GetTenantById;
using Core.Tenant.Features.GetTenantByName;
using Core.Tenant.Features.GetTenants;
using Core.Tenant.Features.PaginationQuery;
using Core.Tenant.Features.UpgradeSubscription;
using Infrastructure.Auth.Policy;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;

namespace Infrastructure.Identity.Tenant.Endpoints;

/// <summary>
/// 租户管理端点
/// </summary>
public static class TenantEndpoints
{
    /// <summary>
    /// 映射租户管理相关API端点
    /// </summary>
    public static IEndpointRouteBuilder MapTenantEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/tenant")
            .WithTags("Tenant")
            .WithDescription("租户管理");

        // -----------------------
        // 创建租户
        // POST /api/tenant
        // -----------------------
        group.MapPost("/", async (
            [FromBody] CreateTenantCommand request,
            [FromServices] IMediator mediator) =>
        {
            var result = await mediator.Send(request);
            return await Result<string>.SucceedAsync(result.Id);
        })
        .RequirePermission("Tenant:Create")
        .WithDescription("创建租户")
        .WithMetadata(new EndpointNameMetadata(nameof(CreateTenantCommand)));

        // -----------------------
        // 获取全部租户
        // GET /api/tenant
        // -----------------------
        group.MapGet("/", async ([FromServices] IMediator mediator) =>
        {
            var data = await mediator.Send(new GetTenantsQuery());
            return await Result<List<TenantDetail>>.SucceedAsync(data);
        })
        .RequirePermission("Tenant:All")
        .WithDescription("查询全部租户")
        .WithMetadata(new EndpointNameMetadata(nameof(GetTenantsQuery)));

        // -----------------------
        // 根据ID获取租户
        // GET /api/tenant/{id}
        // -----------------------
        group.MapGet("/{id}", async (
            string id,
            [FromServices] IMediator mediator) =>
        {
            var data = await mediator.Send(new GetTenantByIdQuery(id));
            return await Result<TenantDetail>.SucceedAsync(data);
        })
        .RequirePermission("Tenant:View:Single")
        .WithDescription("根据ID查询租户")
        .WithMetadata(new EndpointNameMetadata("GetTenantById"));

        // -----------------------
        // 根据名称搜索租户（匿名可访问）
        // GET /api/tenant/search/{name}
        // -----------------------
        group.MapGet("/search/{name}", async (
            string name,
            [FromServices] IMediator mediator) =>
        {
            var data = await mediator.Send(new GetTenantByNameQuery(name));
            return await Result<TenantResponse>.SucceedAsync(data);
        })
        .AllowAnonymous()
        .WithDescription("根据名称查询租户")
        .WithMetadata(new EndpointNameMetadata("GetTenantByName"));

        // -----------------------
        // 分页查询租户
        // GET /api/tenant/page?page=1&size=10
        // -----------------------
        group.MapGet("/page", async (
            [AsParameters] TenantsWithPaginationQuery request,
            [FromServices] IMediator mediator) =>
        {
            var data = await mediator.Send(request);
            return await Result<PaginatedData<TenantDetail>>.SucceedAsync(data);
        })
        .RequirePermission("Tenant:View:Page")
        .WithDescription("分页查询租户")
        .WithMetadata(new EndpointNameMetadata("QueryTenants"));

        // -----------------------
        // 升级租户订阅
        // POST /api/tenant/upgrade
        // -----------------------
        group.MapPost("/upgrade", async (
            [FromBody] UpgradeSubscriptionCommand command,
            [FromServices] IMediator mediator) =>
        {
            var result = await mediator.Send(command);
            return await Result<UpgradeSubscriptionResponse>.SucceedAsync(result);
        })
        .RequirePermission("Tenant:Upgrade")
        .WithDescription("升级租户订阅")
        .WithMetadata(new EndpointNameMetadata(nameof(UpgradeSubscriptionCommand)));

        // -----------------------
        // 激活租户
        // POST /api/tenant/{id}/activate
        // -----------------------
        group.MapPost("/{id}/activate", async (
            string id,
            [FromServices] IMediator mediator) =>
        {
            var result = await mediator.Send(new ActivateTenantCommand(id));
            return await Result<ActivateTenantResponse>.SucceedAsync(result);
        })
        .RequirePermission("Tenant:Activate")
        .WithDescription("激活租户")
        .WithMetadata(new EndpointNameMetadata(nameof(ActivateTenantCommand)));

        // -----------------------
        // 禁用租户
        // POST /api/tenant/{id}/deactivate
        // -----------------------
        group.MapPost("/{id}/deactivate", async (
            string id,
            [FromServices] IMediator mediator) =>
        {
            var result = await mediator.Send(new DisableTenantCommand(id));
            return await Result<DisableTenantResponse>.SucceedAsync(result);
        })
        .RequirePermission("Tenant:Deactivate")
        .WithDescription("禁用租户")
        .WithMetadata(new EndpointNameMetadata(nameof(DisableTenantCommand)));

        // -----------------------
        // 分配租户权限
        // POST /api/tenant/{id}/assign/permission
        // -----------------------
        group.MapPost("/{id}/assign/permission", async (
            string id,
            [FromBody] AssignPermissionToTenantCommand request,
            [FromServices] IMediator mediator) =>
        {
            var result = await mediator.Send(request);
            return result;
        })
        .RequirePermission("Tenant:Assign:Permission")
        .WithDescription("分配租户权限")
        .WithMetadata(new EndpointNameMetadata(nameof(AssignPermissionToTenantCommand)));

        // -----------------------
        // 查询租户权限
        // POST /api/tenant/{id}/permission
        // -----------------------
        group.MapPost("/{id}/permission", async (
            string id,
            [FromBody] GetTenantPermissionByIdQuery request,
            [FromServices] IMediator mediator) =>
        {
            var data = await mediator.Send(request);
            return await Result<IEnumerable<Guid?>>.SucceedAsync(data);
        })
        .RequirePermission("Tenant:Permission:View")
        .WithDescription("查询租户权限")
        .WithMetadata(new EndpointNameMetadata("GetTenantPermissionById"));

        return app;
    }
}
